package com.tanhua.admin.service;


import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.MovementsVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VideoVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class ManagerService {

    @DubboReference
    private UserInfoApi userInfoApi;
    @DubboReference
    private VideoApi videoApi;
    @DubboReference
    private MovementApi movementApi;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /*
     *  分页查询用户列表
     * */
    public PageResult findAllUsers(Integer page, Integer pagesize) {
        IPage iPage = userInfoApi.findAll(page, pagesize);
        List<UserInfo> list = iPage.getRecords();
        for (UserInfo userInfo : list) {
            //获取key
            String key = Constants.USER_FREEZE + userInfo.getId();
            //判断用户是否被冻结
            if (redisTemplate.hasKey(key)) {
                userInfo.setUserStatus("2"); //2表示己冻结
            }

          }
        return new PageResult(page, pagesize, iPage.getTotal(), iPage.getRecords());
            }
        /*
         * 根据id查询用户
         * */
        public UserInfo findUserById (Long userId){
            UserInfo userInfo = userInfoApi.findById(userId);
            //获取用户的key
            String key = Constants.USER_FREEZE + userId;
            //2.判断用户的状态
            if (redisTemplate.hasKey(key)) {
                userInfo.setUserStatus("2");
            }
            return userInfo;
        }
        /*
         * 查询指定用户发布的所有视频,并分页展示
         * */
        public PageResult findAllVideos (Integer page, Integer pagesize, Long uid){
            //根据用户id查询指定用户所有视频
            PageResult pr = videoApi.findByUserId(page, pagesize, uid);
            List<Video> items = (List<Video>) pr.getItems();
            //根据用户id,获取userinfo
            //4、判断列表是否为空
            if (items == null || items.size() <= 0) {
                return pr;
            }
            UserInfo userInfo = userInfoApi.findById(uid);
            //转化为vo对象
            List<VideoVo> list = new ArrayList<>();
            //构造返回
            for (Video item : items) {
                VideoVo vo = VideoVo.init(userInfo, item);
                list.add(vo);
            }
            return new PageResult(page, pagesize, 0l, list);
        }
        //查询动态
        public PageResult findAllMovements (Integer page, Integer pagesize, Long uid, Integer state){
            //1、调用API查询数据 ：Movment对象
            PageResult pageResult = movementApi.findByUserId(uid, state, page, pagesize);
            //2、解析PageResult，获取Movment对象列表
            List<Movement> items = (List<Movement>) pageResult.getItems();
            //3、判断列表是否为空
            if (CollUtil.isEmpty(items)) {
                return new PageResult();
            }
            //4、提取动态发布人的id
            List<Long> userIds = CollUtil.getFieldValues(items, "userId", Long.class);
            //5、根据用户的id获取用户详情
            Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
            //6、一个Movement构造一个vo对象
            List<MovementsVo> vos = new ArrayList<>();
            for (Movement movement : items) {
                UserInfo userInfo = map.get(movement.getUserId());
                if (userInfo != null) {
                    MovementsVo vo = MovementsVo.init(userInfo, movement);
                    vos.add(vo);
                }
            }
            //4、构造返回值
            pageResult.setItems(vos);
            return pageResult;

        }
        /*用户冻结*/
        public Map userFreeze (Map params){
            //获取用户的key
            String userId = (String) params.get("userId");
            String key = Constants.USER_FREEZE + userId;
            //设置失效时间
            Integer freezingTime = Integer.valueOf(params.get("freezingTime").toString());
            //数据存入Redis中
            int days = 0;
            if (freezingTime == 1) {
                days = 3;
            } else if (freezingTime == 2) {
                days = 7;
            }
            //
            String value = JSON.toJSONString(params);
            if (days > 0) {
                redisTemplate.opsForValue().set(key,value,days, TimeUnit.MINUTES);
            } else {
                redisTemplate.opsForValue().set(key, value);
            }
            Map retMap = new HashMap();
            retMap.put("message", "冻结成功");
            return retMap;
        }
        /*用户解冻*/
        public Map userUnfreeze (Map params){
            //解冻的原因未处理，此处未获取：实际开发中要记录冻解和解决的记录日志
            //删除Redis中的数据
            //获取用户的key
            String userId = (String) params.get("userId");
            String key = Constants.USER_FREEZE + userId;
            Boolean delete = redisTemplate.delete(key);
            Map retMap = new HashMap();
            if (delete) {
                retMap.put("message", "解冻成功");
            }
            return retMap;
        }
}

